import datetime
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import time
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime

APISecret=''
APIKey=''

def create_url(your_APIKey, your_APISecret):
    url = 'ws://ws-api.xfyun.cn/v2/iat'
    #url = 'wss://ws-api.xfyun.cn/v2/iat'
    # timestamp
    now = datetime.now()
    date = format_date_time(mktime(now.timetuple()))
    
    signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
    signature_origin += "date: " + date + "\n"
    signature_origin += "GET " + "/v2/iat " + "HTTP/1.1"
    # hmac-sha256 encryption
    signature_sha = hmac.new(your_APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')

    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        your_APIKey, "hmac-sha256", "host date request-line", signature_sha)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

    v = {
        "authorization": authorization,
        "date": date,
        "host": "ws-api.xfyun.cn"
    }
    
    url = url + '?' + urlencode(v)

    return url

if __name__ == "__main__":
    wsUrl = create_url(APIKey, APISecret)
    print(wsUrl)
